package cn.wolfcode.wms.service.impl;

import cn.wolfcode.wms.domain.Role;
import cn.wolfcode.wms.mapper.RoleMapper;
import cn.wolfcode.wms.page.PageResult;
import cn.wolfcode.wms.qo.QueryObject;
import cn.wolfcode.wms.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleService implements IRoleService {



    @Autowired
    private RoleMapper mapper;

    public int deleteByPrimaryKey(Long id) {
        return mapper.deleteByPrimaryKey(id);
    }

    public int insert(Role record) {
        return mapper.insert(record);
    }

    public Role selectByPrimaryKey(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    public List<Role> selectAll() {
        return mapper.selectAll();
    }

    public int updateByPrimaryKey(Role record) {
        return mapper.updateByPrimaryKey(record);
    }


    public void saveorupdate(Role role, Long[] ids, Long[] menuIds) {
        //
        if (role.getId() != null) {
            //更新之前,先删除原有的关系
            mapper.deleteMenuRelation(role.getId());
            //System.out.println(role.getId()+"ppppppppppppppppppppppppppppppppp");
             mapper.deleteRelation(role.getId());
            mapper.updateByPrimaryKey(role);
        } else {
            mapper.insert(role);
        }
        //维护角色与权限之间的关系


            for (Long pId : ids) {
                mapper.insertRelattion(role.getId(),pId);
            }

        for (Long menuId : menuIds) {

            mapper.insertMenuRelation(role.getId(),menuId);
        }
    }

    public void delete(Long id) {
        if(id != null){
            mapper.deleteMenuRelation(id);
            mapper.deleteRelation(id);
            mapper.deleteByPrimaryKey(id);
        }


    }

    public PageResult query(QueryObject qo) {
       int count = mapper.queryForCount(qo);
       if(count == 0){
           return  PageResult.empty(qo.getPageSize());
       }
       List<Role> list = mapper.queryForList(qo);

        PageResult pageResult = new PageResult(qo.getPageSize(), count, qo.getCurrentPage(), list);


        return pageResult;
    }
}

